/**
	工单批量打印模板
*/
public without sharing class WorkorderPDFController {

	public String accId ;//客户的ID
	public List<WorkOrderBean>  woList {get;set;}///选中的工单
	public List<WorkOrderSelectBean> woSelList {get;set;}//可选的工单
	public List<WorkOrderSelectBean> woSelectedList {get;set;}//可选的工单

	public String workOrders {get;set;}//工单
	public List<SelectOption> types {get;set;}//类型
	public WorkOrder__c tempWo {get;set;}//
	//public static Set<String> woSets = new Set<String> ();

	///筛选条件
	public String status {get;set;}//状态
	public String rtype {get;set;}//记录类型
	public String cdate {get;set;}//创建时间
	public String edate {get;set;}//创建时间

    public WorkorderPDFController() {
        woSelectedList = new List<WorkOrderSelectBean>();
        woSelList = new List<WorkOrderSelectBean>();
    }
    public void init(){
    	accId = System.currentPageReference().getParameters().get('accid');
    	workOrders = System.currentPageReference().getParameters().get('wo');
    	 woList= new List<WorkOrderBean>();
    	 tempWo = new WorkOrder__c(Status__c='完成');
    	 getTypes();
    	if(workOrders !=null)getWorkOrderInfo();
    }

    ///获取可选的工单
    public void getWorkOders(){
      woSelList.clear();
    	String sql = 'select Id,Name ,Status__c ,CreatedDate,RecordType.Name from WorkOrder__c where Account__c = \''+ accId +'\'';
    	if (String.isBlank(tempWo.Status__c)== false ) {
    	    sql += ' and Status__c = \'' +tempWo.Status__c+'\'';
    	}
    	if (String.isBlank(rtype)== false ) {
    	   sql += ' and RecordType.Name = \'' +rtype+'\''; 
    	}
    	if (String.isBlank(cdate)== false ) {
    		if(cdate.length() < 12)cdate += 'T00:00:00Z';
    	   sql += ' and CreatedDate >= ' +cdate; 
    	}
    	if (String.isBlank(edate)== false ) {
    		if(edate.length() < 12)edate += 'T00:00:00Z';
    	   sql += ' and CreatedDate <= ' +edate; 
    	}
    	System.debug(sql);

    	for (WorkOrder__c wo: Database.query(sql)) {
    		woSelList.add(new WorkOrderSelectBean(wo));
    	}

    }
    public  void exchange(){
    	Set<Id> extendId = new Set<Id>();

    	List<WorkOrderSelectBean> temp = new List<WorkOrderSelectBean>();
    	for (WorkOrderSelectBean wob : woSelectedList) {
    		if (wob.chk == false ) {
    		    extendId.add(wob.wo.Id);
    		    temp.add(wob);
    		}
    	}

    	woSelectedList.clear();
    	woSelectedList.addAll(temp);

    	for ( WorkOrderSelectBean wob: woSelList) {
    		if (wob.chk == true && !extendId.contains(wob.wo.Id)) {
    		    woSelectedList.add(wob);
    		}
    	}

    }
    ///获取工单的记录类型
   public void getTypes(){
   		types = new List<SelectOption>();
   		 types.add(new SelectOption('','----无----'));

   		for (RecordType rt: [select Id,Name,DeveloperName from RecordType where SObjectType ='WorkOrder__c' and DeveloperName != 'NonAgentInstallationOrder' and DeveloperName != 'Advisory']) {
   			types.add(new SelectOption(rt.Name,rt.Name));

   		}
   }
   ///保存 id 
   public PageReference saveIds (){
   		workOrders = '';
   		for ( WorkOrderSelectBean wob : woSelectedList) {
   			//woSets.add(wob.wo.Id);
   			workOrders += wob.wo.Id +',';

   		}
   		

           
            PageReference ref = new PageReference('/apex/WorkOrderPDf?wo='+workOrders);
            ref.setRedirect(true);
            return workOrders.length() > 1 ? ref : null ;

   }
   public void getWorkOrderInfo(){
   		
   		//System.debug(woSets);
   		System.debug(workOrders);

   		Set<String> woIds = new Set<String>();
   		for (String wo : workOrders.split(',',-1)) {
   			if(wo != null && wo.length() >1)woIds.add(wo);
   		}
   		System.debug(woIds);
   		/*woIds.add('a1F0k000000EbNfEAK');//技术培训
   		woIds.add('a1F0k000000EhKcEAK');//服务报告 
   		woIds.add('a1F28000000hQT7EAM');//保养报告
   		woIds.add('a1F0k000000Lc2TEAS');//安装报告
   		
   		woIds.add('a1F0k000000Ev8GEAS');//仪器培训*/
   			List<WorkOrder__c>	temp  = [ SELECT

   					w.CreatedDate,
                     //工单
                     w.Name,w.Id,
                     //科室负责人
                     w.ManagementDepContact__r.Name,w.ManagementDepContact__r.MobilePhone,
                     //联系人
                     w.Contact__r.Name,w.Contact__r.MobilePhone,
                     //客户
                     w.Account__c,w.Account__r.Name,w.Account__r.Province__r.Name,w.Account__r.Address__c,
                     //产品
                     w.ProductType2__c,w.ServiceManufacture__r.Name,w.ServiceManufacture__r.IMEINumber__c, 
                     w.ServiceManufacture__r.Product__r.Model__c,w.ServiceManufacture__r.Product__r.Name,
                     w.ServiceManufacture__r.EndDate__c,w.ServiceManufacture__r.Brand__c,

                     //结果
                     w.ResultsSuggestions__c,w.ServiceSituation__c,
                     //服务类型
                     w.RecordType.Name,
                     //情况描述
                     w.Reason_Desc__c,
                     //时间
                     w.Install_Start_Datetime__c,w.Install_End_Datetime__c,
                     //创建人
                     w.CreatedBy.Name, w.Technician__r.Name,
                     //记录类型
                     RecordType.DeveloperName,
                     w.Case__r.RecordType.DeveloperName,w.Case__r.ServiceEngineerName__c,
                     //服务工单专用
                     w.Software_Version__c,w.SN__c,w.FaultTypes__c,w.TestPerDay__c,w.NewFaultTypes__c,
                      w.IMEINumber__c,w.IMEINumber_F__c,w.Postcode__c,w.note__c,
                      w.OperationCategory__c,w.InstallRequestDate__c,w.FaultDeals__c,
                      w.Tech_Handle__c,w.ReagentConsumables__c,w.UserDepartmen__c,
                      w.UserDepartmentContact__r.Name,w.UseDeptTeleNo__c,w.WarrantyStatus__c,
        			 w.ActuallyWorkTime__c,w.TechExpense__c,w.TravelExpense__c,
        			 w.TransportTime__c,w.Maintenance_Info__c,w.Fault_Freq__c,w.ProblemType__c,
               ChangeNo__c,

        			 //保养工单
        			 w.Maintenance_Content__c, w.MaintenanceItems__c ,
        			 //安装工单
        			 w.Account__r.Postcode__c,w.Software__c,
        			 Reporter_Version__c,Software_Name__c,DealerNameTxt__c,
        			 Instruction__c,InstallationDebugging__c,ManagementDep__c,ManageDeptTeleNo__c,w.Ship_No__c,
        			 w.ManufactureInfo__r.Name,w.ManufactureInfo__r.Model__c,w.ManufactureInfo__r.SoftwareVersion__c,
        			NormalRequirement1__c,ActualSituation1__c,IsMeetRequirement1__c,
					NormalRequirement2__c,ActualSituation2__c,IsMeetRequirement2__c,
					NormalRequirement3__c,ActualSituation3__c,IsMeetRequirement3__c,
					NormalRequirement4__c,ActualSituation4__c,IsMeetRequirement4__c,
					NormalRequirement5__c,ActualSituation5__c,IsMeetRequirement5__c,
					NormalRequirement6__c,ActualSituation6__c,IsMeetRequirement6__c,
					NormalRequirement7__c,ActualSituation7__c,IsMeetRequirement7__c,
					NormalRequirement8__c,ActualSituation8__c,IsMeetRequirement8__c,
					NormalRequirement9__c,ActualSituation9__c,IsMeetRequirement9__c,
					NormalRequirement10__c,ActualSituation10__c,IsMeetRequirement10__c,  
          NormalRequirement11__c,ActualSituation11__c,IsMeetRequirement11__c             
                     FROM WorkOrder__c w 
                     WHERE w.Id in:woIds and (RecordType.DeveloperName != 'NonAgentInstallationOrder'  and RecordType.DeveloperName !=  'Advisory')];

              Map<Id ,List<WorkOrderProduct__c>> wpMap = new Map<Id ,List<WorkOrderProduct__c>>();
              for (String  woId: woIds) {
              		List<WorkOrderProduct__c> wpTempList = new List<WorkOrderProduct__c>();
              		for (WorkOrderProduct__c wp : [SELECT wp.Id,Product__r.Name,Product__r.NCCode__c,wp.Quantity__c,wp.UnitPrice__c,wp.SalesPrice__c,wp.Name,wp.NewPartsNumber__c ,wp.WorkOrder__c 
        				FROM WorkOrderProduct__c wp 
        				WHERE WorkOrder__c in:woIds]) {

              			if (woId == wp.WorkOrder__c) {
              			    wpTempList.add(wp);
              			}

              		} 
              		wpMap.put(woId, wpTempList);
              }
                


            List<Attachment> attachment= [select body,Name,CreatedDate,Id ,ParentId from Attachment where ParentId = :woIds ];

            Map<Id,Attachment>  attachMap = new Map<Id,Attachment>();
            Map<Id,Attachment>  attachManageMap = new Map<Id,Attachment>();
            Map<Id,Attachment>  attachEngineerMap = new Map<Id,Attachment>();

            for(Attachment att : attachment){
                if (att.Name=='使用科室负责人_Sign.jpg'){
                    //accountSign=att;
                    ///技术服务
                    attachMap.put(att.ParentId, att);
                }else if( att.Name=='管理科室负责人_Sign.jpg'){
                    attachManageMap.put(att.ParentId, att);
                }else if( att.Name == '工程师_Sign.jpg'){
                    attachEngineerMap.put(att.ParentId, att);
                }
            } 

          for (WorkOrder__c wo : temp) {
              woList.add(new WorkOrderBean(wo,attachMap.get(wo.Id),attachManageMap.get(wo.Id),attachEngineerMap.get(wo.Id),wpMap.get(wo.Id)));	
          } 
        

   } 
   	public class WorkOrderSelectBean{
   		public Boolean chk {get;set;}
   		public WorkOrder__c wo {get;set;}
   		public String CreatedDate {get;set;}

   		public WorkOrderSelectBean(WorkOrder__c wor){

   			wo = wor;
   			CreatedDate = wor.CreatedDate.format('YYYY-MM-dd');
   			System.debug(CreatedDate);
   			chk = false;
   		}
   	}	
    public class WorkOrderBean{

    	public WorkOrder__c workOrder {get;private set;}//工单
    	public String CreatedDate {get;set;}
    	public String startTime {get;private set;}//服务开始时间
    	public String endTime {get;private set;}//服务结束时间
    	public String resSugestion {get; private set;}//结果建议
    	public List<String> serviceSituation {get; set;}//服务情况
    	public String deviceName {get; set;}
    	public Attachment useSign {get;set;}//使用科室负责人
    	public Attachment manageSign {get;set;}//管理科室负责人
    	public Attachment engineerSign {get;set;}//工程师

    	public String  type {get; set;}//类型
    	public String responsePerson {get;set;}
    	public String responsePhone{get;set;}
    	public String resionDescrible {get;set;}

    	///---- 服务工单------
    	public List<WorkOrderProduct__c> wpList {get;set;}//工单产品
    	public Decimal partsCost{get;set;}
		public Decimal totalCost{get;set;}
		

		public String useSignDate {get;set;}
		public String manageSignDate {get;set;}
		public String engineerSignDate {get;set;}
		public String  reasonDesc {get;set;}
		public String  note {get;set;}
		public String  maintenanceInfo {get;set;}
		public String  techHandle {get;set;}
		public String  equipmentModel {get;set;}
		public String  equipmentName {get;set;}
		///-------------保养工单
		public List<String> maintenanceContent {set;get;}//保养内容
		public List<String> maintenanceItem {set;get;}//保养项目
		///-------------安装工单
		public String instruction {get;set;}
		public String installationDebugging{get;set;}

		///------------仪器培训工单
		public String deviceNo {get;set;}
		public String accName {get;set;}

    public String serEndTime {get;set;}
    public String serStartTime {get;set;}

    public String engineerName {get;set;}//工程师名字, 经销商工单带个案的服务工程师姓名 ,其他工单带技术人员



    	public WorkOrderBean(WorkOrder__c wor,Attachment att,Attachment matt,Attachment eatt,List<WorkOrderProduct__c> wpL){
    		workOrder = wor;
    		type = findType(workOrder.RecordType.DeveloperName);
    		///-----技术服务工单
    		if(att !=null )useSign = att;
    		 responsePerson = workOrder.ManagementDepContact__r.Name;
             responsePhone = workOrder.ManagementDepContact__r.MobilePhone;

            if(workOrder.Install_Start_Datetime__c != null){
                startTime = workOrder.Install_Start_Datetime__c.format('yyyy年MM月dd日');
            }
            if(workOrder.Install_End_Datetime__c != null){
                endTime = workOrder.Install_End_Datetime__c.format('yyyy年MM月dd日');
            }
            resSugestion = kaigyo(workOrder.ResultsSuggestions__c , 58);
            serviceSituation  =  autoNextLine(workOrder.ServiceSituation__c , 50);
            resionDescrible = kaigyo(workOrder.Reason_Desc__c,50);
            deviceName = kaigyo(workOrder.ServiceManufacture__r.Name, 9);

            // ------- 服务工单
            wpList = wpL;
            partsCost = 0;//零件费

            for(WorkOrderProduct__c wp:wpList){
				partsCost+=(wp.SalesPrice__c==null?0:wp.SalesPrice__c);
			}

			//总费用
			totalCost=0;
			totalCost = partsCost+(workOrder.TechExpense__c==null?0:workOrder.TechExpense__c)+(workOrder.TravelExpense__c==null?0:workOrder.TravelExpense__c);

            //不满4个零件要补齐空行
            Integer atLeastRowsCount = 4;
            if(wpList.size()<atLeastRowsCount){
                Integer wpListSize = wpList.size();
                for(Integer i=0;i<(atLeastRowsCount-wpListSize);i++){
                    wpList.add(new WorkOrderProduct__c());
                }
            }

    		if(matt !=null )manageSign = matt;
    		if(eatt !=null )engineerSign = eatt;
        Set<String> reSet = new Set<String>{'InstallationOrder', 'MaintenanceOrder','ServiceOrder'}; // Defines a new set with two elements
        engineerName = reSet.contains(workOrder.Case__r.RecordType.DeveloperName ) ? workOrder.Case__r.ServiceEngineerName__c : workOrder.Technician__r.Name;
        serStartTime = workOrder.Install_Start_Datetime__c != null ? workOrder.Install_Start_Datetime__c.format('yyyy年MM月dd日'):'';
      serEndTime = workOrder.Install_End_Datetime__c != null ? workOrder.Install_End_Datetime__c.format('yyyy年MM月dd日'):'';
				if(workOrder.Install_End_Datetime__c!= null )useSignDate = serEndTime;
				
			
				if(workOrder.Install_End_Datetime__c!= null )engineerSignDate = serEndTime;
			

			reasonDesc = Utils.wrapWordInPdf(workOrder.Reason_Desc__c, '\n', 30);
			note = Utils.wrapWordInPdf(workOrder.note__c, '\n', 23);
			maintenanceInfo = Utils.wrapWordInPdf(workOrder.Maintenance_Info__c, '\n', 30);
			techHandle = Utils.wrapWordInPdf(workOrder.Tech_Handle__c, '\n', workOrder.RecordType.DeveloperName =='ServiceOrder' ?  20 : 57);
			equipmentModel = Utils.wrapWordInPdf(workOrder.ServiceManufacture__r.Product__r.Model__c, '\n', 9);
			equipmentName = Utils.wrapWordInPdf(workOrder.ServiceManufacture__r.Brand__c,'\n',13);
		///--------保养工单
			maintenanceContent =autoNextLine(workOrder.Maintenance_Content__c,47);
            maintenanceItem = autoNextLine(workOrder.MaintenanceItems__c,47);
         /// --------- 安装工单
            instruction= 			Utils.wrapWordInPdf(workOrder.Instruction__c, 			'\n', 36);
			installationDebugging= 	Utils.wrapWordInPdf(workOrder.InstallationDebugging__c, '\n', 70);
      


     /* reasonDesc = kaigyo(workOrder.Reason_Desc__c, 30);
      note = kaigyo(workOrder.note__c,  23);
      maintenanceInfo = kaigyo(workOrder.Maintenance_Info__c,  30);
      techHandle = kaigyo(workOrder.Tech_Handle__c,  20);
      equipmentModel = kaigyo(workOrder.ServiceManufacture__r.Product__r.Model__c,  9);
      equipmentName = kaigyo(workOrder.ServiceManufacture__r.Product__r.Name,13);
    ///--------保养工单
      maintenanceContent =autoNextLine(workOrder.Maintenance_Content__c,47);
      maintenanceItem = autoNextLine(workOrder.MaintenanceItems__c,47);
         /// --------- 安装工单
      instruction=      kaigyo(workOrder.Instruction__c,  36);
      installationDebugging=  kaigyo(workOrder.InstallationDebugging__c, 50);*/
		// -------记录类型：仪器培训
		 

           
           
            if(workOrder.RecordType.DeveloperName == 'InstrumentsTraining')resSugestion = kaigyo(workOrder.ResultsSuggestions__c , 50);

            deviceNo = kaigyo(workOrder.ServiceManufacture__r.IMEINumber__c, 9);
            accName = kaigyo(workOrder.Account__r.Name, 18);

	
            


    	}
    	private String findType(String type){

    		if (type == 'NonAgentInstallationOrder' || type == 'Advisory') {
        
    			return '';
    		}else if (type == 'ServiceOrder') {
    		    return 'ServiceOrder';

    		}else if (type == 'MaintenanceOrder') {
    			return 'MaintenanceOrder';

    		}else if (type == 'InstrumentsTraining' || type == 'TeachingTraining') {///仪器培训 ,授课
    			return 'InstrumentsTraining';
	    
    		}else if (type == 'InstallationOrder' ) {///
    			return 'InstallationOrder';
	    
    		}

    		return 'Technical';




    	}

    	//计算文本长度自动换行 value字符长度 posLength换行字数
	    private String kaigyo(String value, Integer posLength ){
	        if(value !=null)value = value.replaceAll('\r\n','');
	        if(value == null || value.length() <= posLength) return value;

	        String rtnValue = value.substring(0, posLength ) + '\n';

	        for(Integer i = posLength; i < value.length(); i++){
	            if(Math.mod(i, posLength ) == 0){
	                if(value.length() > i + posLength){
	                    rtnValue += value.substring(i, i + posLength ) + '\n'; 
	                }else{ 
	                    rtnValue += value.substring(i,value.length());
	                } 
	                // kaigyoCount[col]++;
	            }
	        }
	        return rtnValue;
	    }
	    private List<String> autoNextLine(String value, Integer posLength ){
	        List <String> temp = new List<String>();
	        if(value == null ) 
	        {
	            temp.add(value);
	            return temp; 
	        }
	        List<String> str = new List<String>();
	        str =  value.split('\r\n',-1);
	        for (String s :str){

	            if(s.length() > posLength){
	                for(Integer i = 0; i < s.length(); i++){
	                    if(Math.mod(i, posLength ) == 0){
	                        if(s.length() > i + posLength){
	                            temp.add(s.substring(i, i + posLength)); 
	                        }else{ 
	                            temp.add(s.substring(i,s.length()));
	                        } 

	                        // kaigyoCount[col]++;
	                    }
	                }

	            }else{
	                temp.add(s);

	            }
	        }

	        return temp;
	    }    	
    }

    


    
}